import re

from rest_framework import serializers

from goods.models import SKU
from users.utils import generic_verify_url
from .models import User
from django_redis import get_redis_connection
# serializers.ModelSerializer
# serializers.Serializer

# 因为有模型


class RegisterCreateUserSerializer(serializers.ModelSerializer):

    """

    6个参数(mobile,password,password2,username,sms_code,allow)
    """
    # 只进行 反序列化要求的呢??
    # write_only 只在反序列化 输入的时候起作用
    # 在序列化(对象-->字典)的时候 不起作用

    # read_only  只读, 反序列化不使用

    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6, write_only=True)
    allow = serializers.CharField(label='是否同意协议', write_only=True)

    token = serializers.CharField(label='token', read_only=True)
    # ModelSerializer 自动生成字段的时候 是根据 fileds 来生成

    class Meta:
        model = User
        fields = ['mobile','password','username','sms_code','password2','allow']

        # extra_kwargs = {
        #     'id': {'read_only': True},
        #     'username': {
        #         'min_length': 5,
        #         'max_length': 20,
        #         'error_messages': {
        #             'min_length': '仅允许5-20个字符的用户名',
        #             'max_length': '仅允许5-20个字符的用户名',
        #         }
        #     },
        #     'password': {
        #         'write_only': True,
        #         'min_length': 8,
        #         'max_length': 20,
        #         'error_messages': {
        #             'min_length': '仅允许8-20个字符的密码',
        #             'max_length': '仅允许8-20个字符的密码',
        #         }
        #     }
        # }

    """
        对数据的验证有 4中方式:
            1.字段类型
            2.字段选项
            3.单字段校验
            4.多字段校验

        校验手机号   单个字段校验
        是否同意协议 单个字段校验

        密码和确认密码 多个字段
        短信验证码需要多个字段校验

    """
    def validate_mobile(self,value):

        if not re.match('1[3-9]\d{9}',value):
            raise serializers.ValidationError('手机号规则不正确')

        # 最终校验完成之后,要把值返回回去
        return value

    def validate_allow(self,value):

        if value != 'true':
            raise serializers.ValidationError('您未同意协议')

        return value

    def validate(self, attrs):

        # 密码和确认密码
        password = attrs.get('password')
        password2 = attrs.get('password2')
        sms_code = attrs.get('sms_code')
        mobile = attrs.get('mobile')

        if password2 != password:
            raise serializers.ValidationError('密码不一致')
        # 短信验证码需要

        redis_conn = get_redis_connection('code')

        redis_code = redis_conn.get('sms_%s'%mobile)
        if redis_code is None:
            raise serializers.ValidationError('验证码已过期')

        if redis_code.decode() != sms_code:
            raise serializers.ValidationError('验证码不一致')

        return attrs

    def create(self, validated_data):
        # 系统在调用 此方法的时候 , validated_data 多了一些字段,因为 User模型没有那些字段(password2,allow,sms_code)
        # 我们把 validated_data 中的这三个字段删除就可以
        del validated_data['password2']
        del validated_data['allow']
        del validated_data['sms_code']
        user = User.objects.create(**validated_data)

        # 修改密码
        user.set_password(validated_data['password'])
        user.save()

        # 如何生成token, 把代码复制到这里!!!!

        from rest_framework_jwt.settings import api_settings
        # 1.我们需要获取 rest_framework_jwt 的两个方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # 2.将用户信息给 payload,然后进行编码
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token

        return user

# class Person(object):
#     name = 'abc'
#
#
# p1 = Person()
# p1.name='itcast'
# #给对象动态添加属性
# p1.age= 10
#
# p2 = Person()
#
# print(p2.age)

class UserCenterInfoSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email','email_active')

class UserUpdateEmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('email',)

    def update(self, instance, validated_data):


        #保存邮件内容
        email = validated_data.get('email')
        instance.email = email
        instance.save()

        # # 发送激活邮件
        # from django.core.mail import send_mail
        # # #subject, message, from_email, recipient_list,
        # # #subject,   主题
        # subject = '美多商城激活邮件'
        # # # message, 内容
        # message = ''
        # # # from_email,  发件人
        # from_email = '美多商城<liang_xing_hao@163.com>'
        # # # recipient_list, 收件人列表
        # recipient_list = [email]
        #
        # # 我们要生成一个 激活的url
        # # http://ip:port/succes.html?token=xxxx
        # # token 应该包含 用户的信息
        #
        # verify_url = generic_verify_url(instance.id,email)
        # #
        # # 可以设置 丰富的html
        # html_message = '<p>尊敬的用户您好！</p>' \
        #            '<p>感谢您使用美多商城。</p>' \
        #            '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
        #            '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)
        #
        # send_mail(subject=subject,
        #           message=message,
        #           from_email=from_email,
        #           recipient_list=recipient_list,
        #           html_message=html_message)

        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(instance.id, email)


        return instance

from .models import Address
class AddressSerializer(serializers.ModelSerializer):
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')


    def create(self, validated_data):

        """
        因为我们没有让前端将 user_id传递过来,所以我们在进行
        Address.objects.create(**validated_data)的时候,缺少了user
        所以会报错


        """

        validated_data['user'] = self.context['request'].user

        # return Address.objects.create(**validated_data)

        # super() 会调用 ModelSerialzier 的create方法
        return super().create(validated_data)


class UserHistorySerializer(serializers.ModelSerializer):
    sku_id = serializers.CharField(label='商品id', required=True)

    class Meta:
        model = SKU
        fields = ['sku_id']

    def validate(self, attrs):

        # 判断商品id是否存在

        sku_id = attrs.get('sku_id')
        try:
            sku = SKU.objects.get(pk=sku_id)
        except Exception:
            raise serializers.ValidationError('商品不存在')

        return attrs


class SKUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'comments')

